<script setup>
import {
  Promotion,
  Upload,
  Plus
} from '@element-plus/icons-vue'
import { livePostProductService, livePostStartService } from '@/api/live';
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useCameraStore, useUserStore } from '@/stores';
import useStomp from '@/utils/stomp';

const router = useRouter();
const userStore = useUserStore();
const cameraStore = useCameraStore();
const baseURL = import.meta.env.VITE_WS_BASE_URL

const handleStompMessage = (message) => {
  const {type, content} = JSON.parse(message.body);
  if (type === 'CHAT') {
    const contentObj = JSON.parse(content);
    contentObj['time'] = new Date().toLocaleDateString();
    messageArray.value.push(contentObj);
  }
}
// WebSocket
const { connect, isConnected, messageArray, subscribe, send } = useStomp(`${baseURL}/live/api/me/ws?token=Bearer ${userStore.token}`, handleStompMessage);

// RTC
const srsIp = "106.13.105.230"; 
const rtcConfig = {
  // iceServers: [
  //   { 
  //     urls: "stun:47.121.24.225:3478"
  //   },
  //   {
  //     urls: 'turn:47.121.24.225:3478',
  //     username: "yixuan",
  //     credential: "qq2434462503"
  //   }
  // ]
};

// 直播相关状态
let roomId = null;
const isLive = ref(false)
const isMuted = ref(false)
const isCameraOn = ref(true)
const stream = ref(null)
const rtcPeerConnection = ref(null)
const videoElement = ref(null)

// 对话框相关状态
const dialogVisible = ref(false)
const formRef = ref(null)
const liveForm = ref(cameraStore.getLiveFormData());
liveForm.value.coverFile = cameraStore.getCapturedImage();
const coverFileUrl = ref(liveForm.value.coverFile ? URL.createObjectURL(liveForm.value.coverFile) : null);
const formRules = ref({
  title: [
    { required: true, message: '请输入直播标题', trigger: 'blur' },
    { min: 3, max: 30, message: '标题长度在3到30个字符', trigger: 'blur' }
  ]
})

// 聊天相关状态
const newMessage = ref('')
const chatUsers = ref(0)

// 初始化WebRTC
const initWebRTC = async () => {
  try {
    // 获取摄像头和麦克风权限
    stream.value = await navigator.mediaDevices.getUserMedia({ 
      video: true, 
      audio: true 
    })
    
    // 绑定媒体流到video元素
    if (videoElement.value) {
      videoElement.value.srcObject = stream.value
    }

    // 创建RTCPeerConnection    
    rtcPeerConnection.value = new RTCPeerConnection(rtcConfig)
    
    // 添加本地流
    stream.value.getTracks().forEach(track => {
      rtcPeerConnection.value.addTrack(track, stream.value)
    })
    
    // ICE候选处理
    rtcPeerConnection.value.onicecandidate = event => {
      if (event.candidate) {
        // console.log(event.candidate)
        // 发送ICE候选到信令服务器
      }
    }
    
    // 连接状态变化
    rtcPeerConnection.value.onconnectionstatechange = () => {
      // console.log('Connection state:', rtcPeerConnection.value.connectionState)
    }
    
    // 初始化成功
    ElMessage.success('媒体设备初始化成功')
  } catch (error) {
    console.error('媒体设备初始化失败:', error)
    ElMessage.error(`无法访问媒体设备: ${error.message}`)
  }
}

// 打开直播对话框
const openLiveDialog = () => {
  if (!stream.value) {
    ElMessage.warning('请先初始化媒体设备')
    return
  }
  dialogVisible.value = true
}

// 确认开始直播
const confirmStartLive = async () => {
  await formRef.value.validate();
  startLive(liveForm.value);
  dialogVisible.value = false
}

// 开始直播
const startLive = async (liveFormData) => {
  try {
      // 发起请求开启直播
      const res = await livePostStartService(liveFormData);
      roomId = res.data.data;

      // 连接聊天服务器
      connect(`/topic/room.${roomId}`);

      // 创建Offer并设置本地描述
      const offer = await rtcPeerConnection.value.createOffer();
      await rtcPeerConnection.value.setLocalDescription(offer);

      // 发送Offer到SRS的API
      const streamUrl = `webrtc://${srsIp}/live/${roomId}?token=${userStore.token}`;  // 推流地址
      const apiUrl = `https://${srsIp}:1990/rtc/v1/publish/`;
      
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sdp: offer.sdp,
          streamurl: streamUrl,
          api: apiUrl,
          clientip: null
        })
      });

      const answer = await response.json();
      
      // 设置SRS返回的Answer为远程描述
      await rtcPeerConnection.value.setRemoteDescription(
        new RTCSessionDescription({ type: 'answer', sdp: answer.sdp })
      );
      
      // 初始化WebSocket连接
      isLive.value = true
      ElMessage.success(`直播已开始`)
  } catch (error) {
    stopLive();
    ElMessage.error(`开始直播失败: ${error.message}`)
    console.log(error.message)
  }
}

// 停止直播
const stopLive = () => {
  if (rtcPeerConnection.value) {
    rtcPeerConnection.value.close()
    rtcPeerConnection.value = null
  }
  
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop())
    stream.value = null
  }
  
  isLive.value = false
  ElMessage.info('直播已结束')
}

// 切换麦克风状态
const toggleMic = () => {
  if (stream.value) {
    const audioTracks = stream.value.getAudioTracks()
    if (audioTracks.length > 0) {
      audioTracks[0].enabled = !audioTracks[0].enabled
      isMuted.value = !audioTracks[0].enabled
    }
  }
}

// 切换摄像头状态
const toggleCamera = () => {
  if (stream.value) {
    const videoTracks = stream.value.getVideoTracks()
    if (videoTracks.length > 0) {
      videoTracks[0].enabled = !videoTracks[0].enabled
      isCameraOn.value = videoTracks[0].enabled
    }
  }
}

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim()) {
    send(`/app/global/${roomId}`, {type: 0, content: newMessage.value});
    newMessage.value = '';
  }
}

/* 商品 */
const products = ref([
])
const currentProduct = ref(null)

// 添加商品功能状态
const productFormRef = ref(null);
const addProductDialog = ref(false)
const productForm = ref({
  roomId: 0,
  name: '',
  price: 0,
  stock: 1,
  image: '',
})
const productFormRules = ref({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '库存必须大于0', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'blur' }
  ]
})

// 设置当前展示的商品
const setCurrentProduct = (product) => {
  currentProduct.value = product
  ElMessage.success(`正在讲解: ${product.name}`)
  
  send(`/app/global/${roomId}`, {type: 2, content: product.id });
}

// 添加商品
const addProduct = async () => {
  await productFormRef.value.validate();
  productForm.value['roomId'] = roomId; 

  const {id, imageUrl} = (await livePostProductService(productForm.value)).data.data;
  
  const newProduct = {
    id,
    ...productForm.value
  }
  newProduct['image'] = imageUrl;

  products.value.unshift(newProduct)
  ElMessage.success('商品添加成功！')
  
  // 重置表单并关闭对话框
  productForm.value = {
    name: '',
    price: 0,
    stock: 1,
    image: '',
  }
  
  addProductDialog.value = false
}

// 处理图片选择
const uploadImg = ref('');
const handleImageChange = (file) => {
  // 检查文件类型
  const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
  const isImage = validTypes.includes(file.raw.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  
  if (!isImage) {
    ElMessage.error('请上传 JPG/PNG 格式的图片!');
    return;
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return;
  }
  
  // 创建URL对象用于预览
  const reader = new FileReader();
  reader.onload = (e) => {
    uploadImg.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  productForm.value.image = file.raw;
}

// 初始化
onMounted(() => {  
  // 初始化媒体设备但不自动开始直播
  initWebRTC()
})

// 清理
onBeforeUnmount(() => {
  stopLive()
})
</script>

<template>
  <div class="live-container">
    <!-- 顶部导航 -->
    <div class="live-header">
      <div class="brand" @click="router.back()">YH</div>
      <div class="live-status">
        <span :class="['status-indicator', isLive ? 'live' : 'offline']"></span>
        {{ isLive ? '直播中' : '未开播' }}
      </div>
      <div class="user-count">
        <i class="el-icon-user"></i>
        在线观众: {{ chatUsers }}
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧直播区 -->
      <div class="video-section">
        <div class="video-container">
          <video 
            ref="videoElement" 
            autoplay 
            playsinline 
            muted
            class="video-preview"
          ></video>
          
          <div class="overlay-info">
            <div class="viewer-count">
              <i class="el-icon-user-solid"></i> {{ chatUsers }} 人正在观看
            </div>
            <div class="current-product" v-if="currentProduct">
              正在讲解: {{ currentProduct.name }}
            </div>
          </div>
        </div>
        
        <!-- 直播控制 -->
        <div class="controls">
          <el-button 
            :type="isLive ? 'danger' : 'success'" 
            @click="isLive ? stopLive() : openLiveDialog()"
          >
            <i :class="isLive ? 'el-icon-video-pause' : 'el-icon-video-play'"></i>
            {{ isLive ? '结束直播' : '开始直播' }}
          </el-button>
          
          <el-button 
            :type="isMuted ? '' : 'info'" 
            @click="toggleMic"
          >
            <i :class="isMuted ? 'el-icon-microphone-slash' : 'el-icon-microphone'"></i>
            {{ isMuted ? '开启麦克风' : '关闭麦克风' }}
          </el-button>
          
          <el-button 
            :type="!isCameraOn ? '' : 'info'" 
            @click="toggleCamera"
          >
            <i :class="!isCameraOn ? 'el-icon-video-camera-slash' : 'el-icon-video-camera'"></i>
            {{ isCameraOn ? '关闭摄像头' : '开启摄像头' }}
          </el-button>
        </div>
        
        <!-- 商品列表 -->
        <div class="product-list">
          <div class="product-header">
            <h3>直播商品 <el-tag type="info" size="small">点击商品进行讲解</el-tag></h3>
            <el-button type="success" size="small" @click="addProductDialog = true">
              <el-icon><Plus /></el-icon> 添加商品
            </el-button>
          </div>
          <div class="products">
            <div 
              v-for="product in products" 
              :key="product.id"
              class="product-card"
              :class="{ active: currentProduct && currentProduct.id === product.id }"
              @click="setCurrentProduct(product)"
            >
              <img :src="product.image" alt="商品图片">
              <div class="product-info">
                <div class="name">{{ product.name }}</div>
                <div class="price">¥{{ product.price }}</div>
                <div class="sales">库存: {{ product.stock }}件</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧聊天区 -->
      <div class="chat-section">
        <div class="chat-header">
          <i class="el-icon-chat-line-round"></i>
          直播间聊天
          <el-tag type="success" size="small">{{ chatUsers }}人在线</el-tag>
        </div>
        
        <div class="chat-messages">
          <div 
            v-for="message in messageArray" 
            class="message"
          >
            <div class="message-header">
              <span class="username">{{ message.name }}</span>
              <span class="timestamp">{{ message.time }}</span>
            </div>
            <div class="content">{{ message.content }}</div>
          </div>
        </div>
        
        <div class="chat-input">
          <el-input 
            v-model="newMessage" 
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
          >
            <template #append>
              <el-button 
                type="primary" 
                :icon="Promotion" 
                @click="sendMessage"
              >
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
    
    <!-- 底部状态栏 -->
    <div class="live-footer">
      <div class="current-time">
        <i class="el-icon-time"></i> {{ new Date().toLocaleTimeString() }}
      </div>
      <div class="connection-status">
        <i class="el-icon-connection"></i>
        {{ isConnected ? '聊天服务器已连接' : '聊天服务器未连接' }}
      </div>
    </div>

    <!-- 直播标题对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="开始直播"
      width="500px"
      center
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef"
        :model="liveForm" 
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="直播标题" prop="title">
          <el-input 
            v-model="liveForm.title" 
            placeholder="请输入直播标题"
            clearable
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="直播封面" prop="coverFile">
          <el-image style="width: 50%; aspect-ratio: 1/1; cursor: pointer;" :src="coverFileUrl" fit="cover" @click="cameraStore.setLiveFormData(liveForm); router.push('/camera?mode=once')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStartLive">
            开始直播
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加商品对话框 -->
    <el-dialog
      v-model="addProductDialog"
      title="添加商品"
      width="500px"
      center
      :close-on-click-modal="false"
    >
      <el-form 
        :model="productForm" 
        :rules="productFormRules"
        label-width="100px"
        ref="productFormRef"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input 
            v-model="productForm.name" 
            placeholder="输入商品名称"
          />
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input 
            v-model="productForm.price" 
            placeholder="输入商品价格"
            type="number"
            min="0"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="库存数量" prop="stock">
          <el-input 
            v-model="productForm.stock" 
            placeholder="输入库存数量"
            type="number"
            min="1"
          />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="image-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <el-button type="primary" plain>
              <el-icon><Upload /></el-icon>
            </el-button>
          </el-upload>
          
          <div class="image-preview" v-if="productForm.image && uploadImg">
            <el-image 
              :src="uploadImg" 
              fit="cover"
            />
            <div class="preview-text">预览</div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addProductDialog = false">取消</el-button>
          <el-button type="success" @click="addProduct">
            添加商品
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>

<style lang="scss" scoped>
.live-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0f0f13;
  color: #e0e0e0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  overflow: hidden;
}

.live-header {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background: linear-gradient(90deg, #1a1c2b, #222538);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid #2d3045;
  
  .brand {
    cursor: pointer;
    font-size: 20px;
    font-weight: 700;
    background: linear-gradient(90deg, #6a5af9, #d66efd);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-right: 30px;
  }
  
  .live-status {
    display: flex;
    align-items: center;
    margin-right: 20px;
    
    .status-indicator {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 8px;
      
      &.live {
        background: #f44336;
        box-shadow: 0 0 10px #f44336;
      }
      
      &.offline {
        background: #888;
      }
    }
  }
  
  .user-count {
    display: flex;
    align-items: center;
    margin-right: auto;
    
    i {
      margin-right: 5px;
      color: #6a5af9;
    }
  }
}

.main-content {
  display: flex;
  flex: 1;
  padding: 20px;
  gap: 20px;
  overflow: hidden;
}

.video-section {
  flex: 3;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-container {
  position: relative;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
  min-height: 60%;
  
  .video-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    background: #111;
  }
  
  .overlay-info {
    position: absolute;
    bottom: 20px;
    left: 20px;
    right: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .viewer-count {
      background: rgba(0, 0, 0, 0.6);
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 14px;
      color: #fff;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
        color: #6a5af9;
      }
    }
    
    .current-product {
      background: rgba(106, 90, 249, 0.8);
      padding: 6px 15px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 500;
      color: #fff;
    }
  }
}

.controls {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: #1a1c2b;
  border-radius: 12px;
  
  .el-button {
    flex: 1;
    height: 45px;
    font-weight: 600;
    border-radius: 8px;
    border: none;
    background: #25283d;
    color: #e0e0e0;
    transition: all 0.3s;
    
    i {
      margin-right: 8px;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }
}

.product-list {
  background: #1a1c2b;
  border-radius: 12px;
  padding: 15px;
  overflow-y: auto;
  
  .product-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
      margin: 0;
      display: flex;
      align-items: center;
      font-size: 16px;
      color: #d0d0e0;
      
      .el-tag {
        margin-left: 10px;
      }
    }
  }
  
  .products {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding-bottom: 10px;
    max-height: 300px;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      height: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #25283d;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #6a5af9;
      border-radius: 3px;
    }
  }
  
  .product-card {
    min-width: 200px;
    background: #25283d;
    border-radius: 10px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
    border: 2px solid transparent;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
      border-color: #6a5af9;
    }
    
    &.active {
      border-color: #6a5af9;
      box-shadow: 0 0 0 3px rgba(106, 90, 249, 0.3);
    }
    
    img {
      width: 100%;
      height: 100px;
      object-fit: contain;
      background: #333;
    }
    
    .product-info {
      padding: 12px;
      
      .name {
        font-weight: 600;
        margin-bottom: 5px;
        color: #fff;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .price {
        color: #ff6b6b;
        font-weight: 700;
        font-size: 18px;
        margin-bottom: 3px;
      }
      
      .sales {
        font-size: 12px;
        color: #a0a0c0;
      }
    }
  }
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #1a1c2b;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  
  .chat-header {
    padding: 15px 20px;
    background: linear-gradient(90deg, #25283d, #2d3045);
    font-size: 18px;
    font-weight: 600;
    color: #e0e0e0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #2d3045;
    
    i {
      margin-right: 10px;
      color: #6a5af9;
    }
    
    .el-tag {
      margin-left: 10px;
    }
  }
  .chat-messages {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    
    .message {
      margin-bottom: 15px;
      padding: 12px;
      background: #25283d;
      border-radius: 10px;
      border-left: 3px solid #3a3d5d;
      animation: fadeIn 0.3s ease;
      max-width: 90%;
      
      &.system {
        border-left-color: #6a5af9;
        background: rgba(106, 90, 249, 0.1);
        align-self: center;
        max-width: 80%;
      }
      
      &.chat:not(.system) {
        align-self: flex-start;
      }
      
      &.mine {
        align-self: flex-end;
        background: rgba(56, 98, 189, 0.2);
        border-left-color: #3862bd;
      }
      
      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        font-size: 13px;
        
        .username {
          font-weight: 600;
          color: #6a5af9;
          
          &.mine {
            color: #5a93ff;
          }
        }
        
        .timestamp {
          color: #7a7a9a;
          font-size: 12px;
        }
      }
      
      .content {
        color: #d0d0e0;
        line-height: 1.4;
        word-break: break-word;
      }
    }
  }
  
  .chat-input {
    padding: 15px;
    border-top: 1px solid #2d3045;
    background: #25283d;
    
    .el-input {
      border-radius: 8px;
      overflow: hidden;
    }

    .el-button {
      &:hover {
        background-color: rgb(27, 27, 27);
      }
    }
  }
}

.live-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background: #1a1c2b;
  border-top: 1px solid #2d3045;
  font-size: 14px;
  color: #888;
  
  div {
    display: flex;
    align-items: center;
    
    i {
      margin-right: 8px;
    }
  }
}

.el-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-input {
    background: #25283d;
    border: 1px solid #3a3d5d;
    border-radius: 8px;
    color: #e0e0e0;
    
    &:focus {
      border-color: #6a5af9;
    }
  }
  
  .el-dialog__footer {
    padding: 15px 20px 20px;
  }
  
  .image-uploader {
    
    .el-button {
      margin-top: 5px;
    }
    
    .el-upload__tip {
      color: #888;
      font-size: 12px;
      margin-top: 5px;
    }
  }

  .image-preview {
    position: relative;
    width: 150px;
    height: 150px;
    margin-top: 10px;
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid #3a3d5d;
    
    .el-image {
      width: 100%;
      height: 100%;
    }
    
    .preview-text {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0,0,0,0.7);
      color: white;
      text-align: center;
      font-size: 12px;
      padding: 3px 0;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>